<template>
	<el-container>
		<el-header class="header-tabs">
			<el-tabs type="card" v-model="groupId" @tab-change="tabChange">
				<el-tab-pane label="销售单列表" name="1"></el-tab-pane>
				<el-tab-pane label="销售单产品明细" name="2"></el-tab-pane>
			</el-tabs>
		</el-header>
        <el-tabs v-model="statusType" @tab-change="statusChange" v-if="groupId == 1" style="padding-left: 20px;">
            <el-tab-pane label="已审核" name="1"></el-tab-pane>
            <el-tab-pane label="待审核" name="0"></el-tab-pane>
            <el-tab-pane label="全部" name="-1"></el-tab-pane>
        </el-tabs>
		<el-header style="border-bottom: none;">
			<div class="left-panel">
				<el-button type="primary" icon="el-icon-plus" v-auth="'contract.add'" @click="add" v-if="groupId == '1'"></el-button>
				<el-button type="danger" plain icon="el-icon-delete" v-auth="'contract.delete'" :disabled="selection.length == 0" @click="batch_del" v-if="groupId == '1'"></el-button>
				<el-button type="warning" plain v-auth="'contract.check'" :disabled="selection.length == 0" @click="batch_check" v-if="groupId == '1' && statusType == 0">审核</el-button>
				<el-button type="info" plain v-auth="'contract.uncheck'" @click="batch_uncheck" :disabled="selection.length == 0" v-if="groupId == '1' && statusType == 1">反审核</el-button>
                <el-button type="warning" plain v-auth="'procure.export'" :disabled="selection.length != 1" @click="exportExport" v-if="groupId == '1'">导出</el-button>
				<sc-export-button :auth="'contract.detailsExport'" :apiObj="shopObj" :search="search" v-if="groupId == 2"></sc-export-button>
				<sc-print-button :auth="'contract.print'" :selection="selection"></sc-print-button>
                <sc-import-button v-if="groupId == 1" :auth="'contract.impoet'" :apiObj="importObj" :base="base + '/file_templets/temples_product.xls'" @importSuccess="importSuccess"></sc-import-button>
                <div class="finish" v-if="groupId == 1">
                    <div class="finishNum">销售总额:<div class="text">{{total_money}}</div></div>
                </div>
			</div>
			<div class="right-panel">
				<div class="right-panel-search">
				</div>
			</div>
		</el-header>
        <el-header>
			<div class="left-panel">
			</div>
			<div class="right-panel">
				<div class="right-panel-search">
					<el-date-picker v-model="search.open_single" :value-format="'YYYY-MM-DD'" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 230px"/>
					<el-input v-model="search.contract_code" placeholder="请输入销售单号" clearable @keyup.enter="upsearch"></el-input>
                    <el-select v-model="search.customer_id" placeholder="请选择客户" filterable clearable>
                        <el-option v-for="item in clientList" :key="item.id" :label="item.customer_name" :value="item.id"></el-option>
                    </el-select>
					<el-input v-model="search.goods_name" placeholder="请输入产品名称" clearable @keyup.enter="upsearch" v-if="groupId == '2'"></el-input>
					<el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
					<el-button type="primary" icon="el-icon-refresh" @click="refresh"></el-button>
				</div>
			</div>
		</el-header>
		<el-main class="nopadding" v-if="groupId == '1'">
			<scTable ref="table" row-key="id" :apiObj="apiObj" @selection-change="selectionChange" stripe remoteSort remoteFilter border :params="query" @setExtend="setExtend">
				<el-table-column type="selection" width="50" reserve-selection align="center"></el-table-column>
				<el-table-column type="index" label="序号" fixed align="center" width="50"></el-table-column>
				<el-table-column label="销售单号" prop="contract_code" align="center"></el-table-column>
                <el-table-column label="明细表" type="expand" prop="expand" align="center" width="70">
                    <template #default="props">
                        <div m="4">
                            <scTable :data="props.row.product" hidePagination hideDo border>
                                <el-table-column width="150" />
                                <el-table-column label="产品编码" prop="goods.goods_code" width="150" />
                                <el-table-column label="产品型号" prop="goods.goods_name" width="150" />
                                <el-table-column label="箱号" prop="box_code" width="150" />
                                <el-table-column label="品类" prop="goods.cate.cate_name" width="150" />
                                <el-table-column label="数量" prop="sale_num" width="150" />
                                <el-table-column label="金额" prop="price" width="150" />
                                <el-table-column label="总价" prop="total_price" width="150" />
                            </scTable>
                        </div>
                    </template>
                </el-table-column>
				<el-table-column label="客户" prop="customer_name" align="center" sortable>
                    <template #default="scope">
                        {{scope.row.customer.customer_name}}
                    </template>
                </el-table-column>
				<el-table-column label="审核状态" prop="status" align="center">
					<template #default="scope">
						<el-tag type="warning" v-if="scope.row.status == 0">待审核</el-tag>
						<el-tag type="success" v-if="scope.row.status == 1">通过</el-tag>
						<el-popover placement="top-start" :width="200" trigger="hover" :content="scope.row.reason">
							<template #reference>
								<el-tag type="danger" v-if="scope.row.status == 2">驳回</el-tag>
							</template>
						</el-popover>
						<!-- <el-tag :type="scope.row.status == 0 ? 'warning' : scope.row.status == 1 ? 'success' : 'danger'">{{scope.row.status == 0 ? '待审核' : scope.row.status == 1 ? '通过' : '驳回'}}</el-tag> -->
					</template>
				</el-table-column>
				<el-table-column label="订单状态" prop="contract_status" align="center">
					<template #default="scope">
						<el-tag :type="scope.row.contract_status == 0 ? 'primary' : scope.row.contract_status == 1 ? 'success' : 'danger'">
							{{ scope.row.contract_status == 0 ? '进行中' : scope.row.contract_status == 1 ? '已完成' : '已作废' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="备注" prop="remark" align="center">
					<template #default="scope">
						<el-popover placement="top-start" :width="200" trigger="hover" :content="scope.row.remark">
							<template #reference>
								<el-button style="padding: 5px 0;font-size: 12px" text class="m-2">{{ scope.row.remark && scope.row.remark.substring(0, 10) }}</el-button>
							</template>
						</el-popover>
					</template>
				</el-table-column>
				<el-table-column label="开单日期" prop="open_single" align="center" sortable></el-table-column>
				<el-table-column label="销售交期" prop="deliver_date" align="center"></el-table-column>
				<el-table-column label="销售金额" prop="contract_price" align="center" width="85"></el-table-column>
				<el-table-column label="累计收款" prop="pay_price" align="center" width="85"></el-table-column>
				<el-table-column label="操作" fixed="right" align="center" width="200">
					<template #default="scope">
						<el-button-group>
							<el-button text type="primary" size="small" @click="table_show(scope.row, scope.$index)" v-auth="'contract.show'">查看</el-button>
							<el-button text type="primary" size="small" @click="table_edit(scope.row, scope.$index)" v-auth="'contract.edit'" v-if="scope.row.status != 1">编辑
							</el-button>
							<el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row, scope.$index)">
								<template #reference>
									<el-button text type="danger" size="small" v-auth="'contract.delete'" v-if="scope.row.status != 1">删除</el-button>
								</template>
							</el-popconfirm>
							<el-popconfirm title="确定作废吗?" @confirm="table_cancel(scope.row)">
								<template #reference>
									<el-button text type="info" size="small" v-auth="'contract.cancel'" v-if="scope.row.status == 1 && scope.row.contract_status == 0">作废
									</el-button>
								</template>
							</el-popconfirm>
                            <el-button text type="primary" size="small" @click="table_bill(scope.row)" v-auth="'procure.show'">查看INVOICE</el-button>
							<el-button text type="warning" size="small" @click="table_copy(scope.row, scope.$index)">复制订单</el-button>
						</el-button-group>
					</template>
				</el-table-column>
			</scTable>
		</el-main>
		<el-main class="nopadding" v-if="groupId == '2'">
			<scTable ref="table" row-key="id" :apiObj="shopObj" @selection-change="selectionChange" stripe remoteSort remoteFilter border :params="query">
				<el-table-column type="selection" width="50" reserve-selection align="center"></el-table-column>
				<el-table-column type="index" label="序号" fixed align="center" width="50"></el-table-column>
				<el-table-column label="销售单号" prop="contract_code" align="center"></el-table-column>
				<el-table-column label="客户名称" prop="customer_name" align="center"></el-table-column>
				<el-table-column label="品类" prop="goods.cate.cate_name" align="center"></el-table-column>
				<el-table-column label="产品型号" prop="goods.goods_name" align="center"></el-table-column>
				<el-table-column label="产品编码" prop="goods.goods_code" align="center"></el-table-column>
				<el-table-column label="产品单位" prop="goods.unit.unit_name" align="center"></el-table-column>
				<el-table-column label="数量" prop="sale_num" align="center"></el-table-column>
				<el-table-column label="单价" prop="price" align="center"></el-table-column>
				<el-table-column label="总价" prop="total_price" align="center"></el-table-column>
				<el-table-column label="开单日期" prop="open_single" align="center"></el-table-column>
				<el-table-column label="销售交期" prop="deliver_date" align="center"></el-table-column>
			</scTable>
		</el-main>
	</el-container>
	<save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save = false"></save-dialog>
	<check-status v-if="dialog.check" ref="checkDialog" @success="handleSuccess" @closed="dialog.check = false"></check-status>
	<save-production v-if="dialog.production" ref="productionDialog" @success="handleSuccess" @closed="dialog.production = false"></save-production>
    <bill-save v-if="dialog.bill" ref="billDialog" @success="handleSuccess" @closed="dialog.bill=false"></bill-save>
	<plan-save v-if="dialog.plan" ref="planDialog" @success="handleSuccess" @closed="dialog.plan = false"></plan-save>
</template>

<script>
import SaveProduction from '@/views/production/plan/save.vue'
import CheckStatus from './checkStatus.vue'
import saveDialog from './save'
import BillSave from './billSave.vue'
import planSave from '@/views/procure/plan/save.vue'

export default {
	name: '销售单',
	components: {
		saveDialog, CheckStatus, SaveProduction, planSave, BillSave
	},
	data() {
		return {
			dialog: {
				save: false,
				check: false,
				production: false,
				plan: false,
			},
			apiObj: this.$API.contract.contract.list,
			shopObj: this.$API.contract.contract.detailList,
            importObj: this.$API.contract.contract.import,
			selection: [],
			search: {
				contract_code: null,
				customer_id: null,
				status: null,
				contract_status: null,
			},
			groupId: "1",
            statusType: "1",
			form: {},
            query: {
                status: 1
            },
            total_money: "",
            clientList:[],
		}
	},
	mounted() {
        this.getClient()
	},
	methods: {
        setExtend(data){
            this.total_money = data
        },
        async exportExport(){
            var res = await this.$API.contract.contract.packexport.post({id:this.selection[0].id});
            if (res.code == 1) {
                const fileUrl = res.data;
                const link = document.createElement("a");
                link.href = fileUrl;
                link.download = fileUrl;
                link.click();
            } else {
                this.$alert(res.message, "提示", { type: "error" });
            }
        },
		//添加
		add() {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open('add')
			})
		},
		//编辑
		table_edit(row) {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open('edit').setData(row)
			})
		},
		//查看
		table_show(row) {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open('show').setData(row)
			})
		},
        // 查看Invoice
		table_bill(row) {
			this.dialog.bill = true
			this.$nextTick(() => {
				this.$refs.billDialog.open('show').setData(row)
			})
		},
		// 审核
		table_check(row) {
			this.dialog.check = true
			this.$nextTick(() => {
				this.$refs.checkDialog.open('edit').setData(row)
			})
		},
		//反审核
		async table_uncheck(row) {
			var reqData = {id: [row.id], status: 0}
			var res = await this.$API.contract.contract.check.post(reqData);
			if (res.code == 1) {
				this.$refs.table.refresh()
				this.$message.success("操作成功")
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		//作废
		async table_cancel(row) {
			var reqData = {id: [row.id], status: 0}
			var res = await this.$API.contract.contract.cancel.post(reqData);
			if (res.code == 1) {
				this.$refs.table.refresh()
				this.$message.success("操作成功")
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		// 生产
		table_production(row) {
			this.dialog.production = true
			this.$nextTick(() => {
				this.$refs.productionDialog.open('production').goProduction(row)
			})
		},
		// 发起采购计划
		table_go_plan(row) {
			this.dialog.plan = true
			this.$nextTick(() => {
				this.$refs.planDialog.open('sale').saleCome(row)
			})
		},
		//删除
		async table_del(row, index) {
			var reqData = {id: row.id}
			var res = await this.$API.contract.contract.delete.post(reqData);
			if (res.code == 1) {
				this.$refs.table.tableData.splice(index, 1);
				this.$refs.table.refresh()
				this.$message.success("删除成功")
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		async table_del_all(delete_ids) {
			var reqData = {id: delete_ids}
			var res = await this.$API.contract.contract.delete.post(reqData);
			if (res.code == 1) {
				this.$refs.table.refresh()
				this.$message.success("删除成功")
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		//批量删除
		async batch_del() {
			var delete_ids = [];
			this.selection.forEach((item) => {
				delete_ids.push(item.id)
			})
			this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, '提示', {
				type: 'warning'
			}).then(() => {
				this.table_del_all(delete_ids)
			}).catch(() => {

			})
		},
		batch_check() {
			var ids = [];
			let go = true
			this.selection.forEach((item) => {
				if (item.status != 0) {
					go = false
				} else {
					ids.push(item.id)
				}
			})
			if (!go) {
				this.$message.error("请选择未审核的订单")
				return
			}
			this.dialog.check = true
			this.$nextTick(() => {
				this.$refs.checkDialog.open('edit').setData(ids)
			})
		},
		async batch_uncheck() {
			var ids = [];
			this.selection.forEach((item) => {
				ids.push(item.id)
			})
			this.$confirm(`确定反审核选中的 ${this.selection.length} 项吗？`, '提示', {
				type: 'warning'
			}).then(async () => {
				var reqData = {id: ids}
				var res = await this.$API.contract.contract.uncheckStatus.post(reqData);
				if (res.code == 1) {
					this.$refs.table.refresh()
					this.$message.success("操作成功")
				} else {
					this.$alert(res.message, "提示", {type: 'error'})
				}
			}).catch(() => {

			})
		},
		//表格选择后回调事件
		selectionChange(selection) {
			this.selection = selection;
		},
		//搜索
		upsearch() {
			this.$refs.table.upData(this.search)
		},
		refresh() {
			for (const key in this.search) {
				this.search[key] = null;
			}
			this.$refs.table.upData(this.search)
		},
		//本地更新数据
		handleSuccess(data, mode) {
			if (mode == 'add') {
				this.$refs.table.refresh()
			} else if (mode == 'edit') {
				this.$refs.table.refresh()
			} else if (mode == 'production') {
				this.$refs.table.refresh()
			} else if (mode == 'sale') {
				this.$refs.table.refresh()
			} else if (mode == 'copy') {
				this.$refs.table.refresh()
			}
		},
		async check(e) {
			var reqData = {id: e, status: 1}
			var res = await this.$API.contract.contract.check.post(reqData);
			if (res.code == 1) {
				this.$refs.table.refresh()
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		async table_copy(row) {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open('copy').setCopy(row)
			})
		},
        tabChange(){
            this.query.status = null
        },
        statusChange(e){
            if(e == -1){
                this.search.status = null
            }else{
                this.search.status = e
            }
            this.upsearch()
        },
        // 客户列表
        async getClient(){
            var res = await this.$API.client.client.all.get();
            this.clientList = res.data
        },
	}
}
</script>

<style></style>
